package com.huantai.common.util.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 反射工具类
 * 
 * @author Ma Chao
 * @version 2018年7月23日 下午2:43:44
 */
public class ReflectUtil {
    private ReflectUtil() {}

    /**
     * 获得对象的属性集合
     * 
     * @param obj 对象
     * @return 属性集合
     * @throws Exception
     */
    public static List<Field> getFields(Object obj) {
        Field[] fields = obj.getClass().getDeclaredFields();
        return Arrays.asList(fields);
    }

    /**
     * 获得对象的属性名、值对Map
     * 
     * @param obj 类对象
     * @param withNullValue 是否需要值为空的属性
     * @return key=属性名，value=属性值的Map
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static Map<String, Object> getFieldsNameValue(Object obj, boolean withNullValue)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Map<String, Object> result = new HashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();
        int length = fields.length;
        for (int j = 0; j < length; j++) {
            String name = fields[j].getName();
            String getMethodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method getMethod = obj.getClass().getMethod(getMethodName);
            if (null != getMethod) {
                Object value = getMethod.invoke(obj);
                if ((null == value && withNullValue) || null != value) {
                    result.put(name, value);
                }
            }
        }
        return result;
    }


    /**
     * 获得对象的属性名、值对Map
     * 
     * @param obj 类对象
     * @param sortFields 属性名是否需要字典排序
     * @param withNullValue 是否需要值为空的属性
     * @return key=属性名，value=属性值的Map
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static Map<String, Object> getFieldsNameValue(Object obj, boolean sortFields, // NOSONAR
            boolean withNullValue)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        // 有序的Map
        Map<String, Object> result = new LinkedHashMap<>();
        // 取对象的属性
        Field[] fields = obj.getClass().getDeclaredFields();
        int length = fields.length;
        // 需要按属性排序时
        if (sortFields) {
            List<String> fieldNames = new ArrayList<>();
            for (int i = 0; i < length; i++) {
                Field field = fields[i];
                String name = field.getName();
                fieldNames.add(name);
            }
            // 排序
            Collections.sort(fieldNames, new Comparator() { // NOSONAR
                @Override
                public int compare(Object o1, Object o2) {
                    String str1 = (String) o1;
                    String str2 = (String) o2;
                    if (str1.compareToIgnoreCase(str2) < 0) {
                        return -1;
                    }
                    return 1;
                }
            });
            // 按排序后的属性取值放入有序的Map
            for (String name : fieldNames) {
                String getMethodName =
                        "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
                Method getMethod = obj.getClass().getMethod(getMethodName);
                if (null != getMethod) {
                    Object value = getMethod.invoke(obj);
                    if ((null == value && withNullValue) || null != value) {
                        result.put(name, value);
                    }
                }
            }
        } else {
            result = getFieldsNameValue(obj, withNullValue);
        }
        return result;
    }
}
